const sizeOf = require('image-size')
function getImageSizeFromBase64(base64String) {
    return new Promise((resolve, reject) => {
        try {
            // 去掉 Base64 前缀
            const base64Data = base64String.split(',')[1] || base64String
            // 将 Base64 字符串转换为 Buffer
            const buffer = Buffer.from(base64Data, 'base64')
            // 获取图像尺寸
            const dimensions = sizeOf(buffer)
            // 计算原始二进制数据的长度（字节数）
            const byteLength = buffer.length
            // 转换为 KB
            const sizeInKB = byteLength / 1024
            resolve({
                width: dimensions.width,
                height: dimensions.height,
                size: Math.ceil(sizeInKB),
            })
        } catch (error) {
            reject(new Error('Failed to load image from Base64 string'))
        }
    })
}

function getCookieValue(cookieString, cookieName) {
    const name = cookieName + '='
    const decodedCookie = decodeURIComponent(cookieString)
    const ca = decodedCookie.split(';')
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i]
        while (c.charAt(0) === ' ') {
            c = c.substring(1)
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length)
        }
    }
    return ''
}

function parseCookies(cookieArray) {
    const cookies = {};

    cookieArray.forEach(cookieStr => {
        const [cookiePart] = cookieStr.split(';');  // 获取键值对部分，不包括其他属性
        const [key, value] = cookiePart.split('=');  // 按 '=' 分割键和值
        if (key && value) {
            cookies[key.trim()] = value.trim();  // 去除可能的空格，并存入对象
        }
    });

    return cookies;
}

module.exports = {
    getImageSizeFromBase64,
    getCookieValue,
    parseCookies
}
